import React, { Component } from 'react'
import { NavBar, Icon, List, InputItem, Button } from 'antd-mobile'
import { connect } from 'dva'
import { createForm } from 'rc-form';
import { routerRedux } from 'dva/router'
const ListItem = List.Item
import request from '../../utils/request'

@connect(({ global }) => ({ 当前用户: global.当前用户 }))
@createForm()
class App extends Component {
    constructor(props) {
        super(props)
        const { field } = props.match.params
        this.state = {
            参数: "F" + field,
            标题: field,
            错误信息: ""
        }
    }

    handleSubmit = () => {
        const { dispatch, form, 当前用户 } = this.props
        const { 参数 } = this.state
        form.validateFields((err, values) => {
            if (!err) {
                request("用户/更新", {
                    key: 参数,
                    value: values.内容
                }, () => {
                    当前用户[参数] = values.内容
                    dispatch({ type: 'global/save', 当前用户 })
                    dispatch(routerRedux.goBack())
                }, (code, msg) => {
                    this.setState({ 错误信息: msg })
                })
            } else {
                this.setState({ 错误信息: err.内容.errors[0].message })
            }
        })
    }
    render() {
        const { dispatch, 当前用户 } = this.props
        const { 标题, 参数, 错误信息 } = this.state
        const { getFieldProps } = this.props.form;
        let inputType = ""
        if (参数 == "F手机") {
            inputType = "phone"
        }
        const rules = [
            {
                required: true
            }
        ]
        if (参数 == "Email") {
            rules.push({ type: 'email' })
        }
        return (
            <div>
                <NavBar
                    mode="light"
                    icon={(<Icon type="left" />)}
                    onLeftClick={() => dispatch(routerRedux.push("/商家"))}>更新{标题}</NavBar>
                <List>
                    {错误信息 && (
                        <label
                            style={{
                                color: 'red',
                                padding: 10
                            }}>{错误信息}</label>
                    )}
                    <InputItem
                        {...getFieldProps('内容', { initialValue: 当前用户[参数], rules: rules }) }
                        clear
                        placeholder={标题}
                        type={inputType}>{标题}</InputItem>
                    <ListItem>
                        <Button
                            type="primary"
                            style={{
                                marginRight: 10
                            }}
                            onClick={this.handleSubmit}>
                            确定
                        </Button>
                    </ListItem>
                </List>
            </div>
        )
    }
}

export default App
